import axios from 'axios'
import { Message } from 'element-ui';
import router from '../router'

/**
 * 网络请求封装
 */

axios.interceptors.response.use(success => {
    if(success.status && success.status == 200 && success.data.status == 500) {
        Message.error({message: success.data.msg});
        return;
    }
    if(success.status && success.status == 200 && (success.data.status + '').length == 5) {
        // console.log(success.data.status);
        Message.error({message: success.data.msg});
        return;
    }
    if(success.data.msg) {
        Message.success({message: success.data.msg})
    }
    return success.data;
},error => {
    if(error.response.status == 504 || error.response.status == 404) {
        Message.error({message: "服务器被吃了~"});
    }else if(error.response.status == 403) {
        Message.error({message: "权限不足!"})
    }else if(error.response.status == 401) {
        Message.error({message: "尚未登录,请登录!"})
        router.replace("/");
    }else {
        if(error.response.data.message) {
            Message.error({message: error.response.data.msg});
        }else {
            Message.error({message: "未知错误!"})
        }
    }
    return;
})

// 前缀
let base = '';

/**
 * 请求application/x-www-form-urlencoded类型的数据
 * post请求
 * @param {*} url  地址
 * @param {*} params 请求参数,是key:value形式,参考Login.vue
 */
export const postKeyValueRequest = (url,params) =>{
    return axios({
        method: 'post',
        url:  `${base}${url}`,
        data: params,
        transformRequest: [function(data) {
            let ret = '';
            for(let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            } 
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}


/**
 * 请求json类型的数据
 * post请求
 * @param {*} url url
 * @param {*} params json
 */
export const postRequset = (url,params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params
    })
}

/**
 * 请求json类型的数据
 * put请求
 * @param {*} url 地址
 * @param {*} params json
 */
export const putRequset = (url,params) => {
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params
    })
}

/**
 * 请求json类型的数据
 * get请求
 * @param {*} url 地址
 * @param {*} params json
 */
export const getRequset = (url,params) => {
    return axios({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
}

/**
 * 请求json类型的数据
 * delete请求
 * @param {*} url 地址
 * @param {*} params json
 */
export const deleteRequset = (url,params) => {
    return axios({
        method: 'delete',
        url: `${base}${url}`,
        data: params
    })
}